<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, Ref, watch } from 'vue';

import { useECharts } from '@/hooks/web/useECharts';
import { getLastMonthDayFee, getLastMonthDayFeeByGoodsType } from '@/api/weight/weight';
import { basicProps } from './props';


interface LastMonthDayFeeItem {
  dateStr: string;
  totalSum: number;
  weightFeeSum:number;
}

const lastMonthDayFeeData = ref<LastMonthDayFeeItem[]>([]);


export default defineComponent({
  props: {
    ...basicProps,
    selectedGoodsType: {
      type: Number,
      default: null
    }
  },
  setup(props) {
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

    // 获取数据并更新图表
    const loadData = async () => {
      try {
        let response;
        if (props.selectedGoodsType) {
          // 如果有选中的商品类型，调用筛选API
          response = await getLastMonthDayFeeByGoodsType(props.selectedGoodsType);
        } else {
          // 否则调用默认API
          response = await getLastMonthDayFee();
        }
        
        // 假设API返回的格式是{data: [...]}，如果不是则根据实际情况调整
        if (response && response.data) {
          lastMonthDayFeeData.value = response.data;
          updateChart();
        } else if (Array.isArray(response)) {
          lastMonthDayFeeData.value = response;
          updateChart();
        }
      } catch (error) {
        console.error('获取上月费用数据失败:', error);
      }
    };

    // 更新图表配置
    const updateChart = () => {
      if (lastMonthDayFeeData.value.length === 0) {
        // 如果没有数据，显示空状态
        setOptions({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            data: []
          },
          yAxis: {},
          series: [],
          graphic: [
            {
              type: 'text',
              left: 'center',
              top: 'middle',
              style: {
                text: '暂无数据',
                fontSize: 14,
                fill: '#999'
              }
            }
          ]
        });
        return;
      }

      // 提取x轴数据（日期）和series数据（totalSum和weightFeeSum）
      // 先对数据按日期进行排序，确保x轴始终有序
      const sortedData = [...lastMonthDayFeeData.value].sort((a, b) => {
        return new Date(a.dateStr) - new Date(b.dateStr);
      });
      
      const xAxisData = sortedData.map(item => item.dateStr);
      const totalSumData = sortedData.map(item => item.totalSum);
      const weightFeeSumData = sortedData.map(item => item.weightFeeSum);

      setOptions({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['货物总价', '总过磅费'],
          top: 0
        },
        grid: {
          top: 30,
          bottom: 30,
          left: '3%',
          right: '4%',
          containLabel: true
        },
        xAxis: {
          data: xAxisData,
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '货物总价',
            type: 'bar',
            data: totalSumData,
            label: {
              show: true,
              position: 'top',
              formatter: '{c}',
              distance: 0 // 距离图形的距离（像素）
            }
          },
          {
            name: '总过磅费',
            type: 'bar',
            data: weightFeeSumData,
            label: {
              show: true,
              position: 'top',
              formatter: '{c}',
              distance: 0 // 距离图形的距离（像素）
            }
          }
        ]
      });
    };

    // 监听selectedGoodsType的变化，当它变化时重新加载数据
    watch(() => props.selectedGoodsType, () => {
      loadData();
    });

    onMounted(() => {
      loadData();
    });
    return { chartRef };
  },
});
</script>
